<!--
 * @Author       : wfl
 * @LastEditors: qiye
 * @description  :
 * @updateInfo   :
 * @Date         : 2022-11-15 10:51:43
 * @LastEditTime: 2024-02-04 11:33:06
-->
<script lang="ts" setup name="ApplicationDevelop">
import useUserStore from '@g/store/modules/user'
import { ikStore } from 'iking-utils'
import EditPage from './EditPage.vue'
import { api } from '@/MainApp/apis/application'

const userStore = useUserStore()

const config = useConfig()
const limitLength = useLength()

console.log('config ', config)

console.log('limitLength ', limitLength)

const { t } = useConfig()

const { msgError, msgSuccess, msgBoxWarnAsync } = useMessage()

const state = reactive<any>({
  // 视图：'table' | 'details'
  view: 'table',
  row: null,
  searchData: {},
  tableData: [],
  fields: [
    {
      // 图标、名称、类型
      key: 'name',
      value: '',
      label: '应用名称',
      width: 170,
      tableSlot: 'name',
      search: true,
      show: true
    },
    {
      key: 'typeName',
      value: '',
      label: '类型',
      search: false,
      show: true
    },
    {
      key: 'remark',
      value: '',
      label: '应用说明',
      search: false,
      show: true
    },

    {
      key: '',
      label: '操作',
      show: true,
      width: 150,
      tableSlot: 'operate',
      fixed: 'right',
      showOverflowTooltip: false
    }
  ],
  total: 0

})

const methods = {
  search: async () => {
    const params = {
      ...state.searchData,
      tenantCode: userStore?.tenant?.code || ikStore.local.getItem(ELocal.TENANT)?.code
    }
    const res = await api.select(params)
    if (!res.success) {
      msgError(res.msg)
      return
    }
    state.tableData = res.data
    state.total = res.total
  },
  disable: async (row: any) => {
    const res = await api.disable(row.id)
    if (!res.success) {
      msgError(res.msg)
      return
    }
    msgSuccess(res.msg)
    methods.search()
  },
  enable: async (row: any) => {
    const res = await api.enable(row.id)
    if (!res.success) {
      msgError(res.msg)
      return
    }
    msgSuccess(res.msg)
    methods.search()
  },
  remove: async (row: any) => {
    const res = await api.remove(row.id)
    if (!res.success) {
      msgError(res.msg)
      return
    }
    methods.search()
  },
  showTable: () => {
    state.view = 'table'
    methods.search()
  }
}

/** 编辑对话框  begin */
/** 新增 、 编辑 表单 */
const typeOptions = ref([
  { label: '平台应用', value: 'PLATFORM' },
  { label: '第三方应用', value: 'THIRD_PARTY' }
])
const editFormRef = ref<any>(null)
class EditForm {
  id: string = ''
  // 应用名称
  name: string = ''
  // PLATFORM | THIRD_PARTY
  type: string = 'PLATFORM'
  // 首页地址
  indexPath: string = ''
  // 图标
  icon: string = ''
  // 描述
  remark: string = ''
}
const editForm = reactive(new EditForm())
const editState = reactive({
  loading: false,
  operation: 'add',
  title: '新增',
  visible: false,
  defaultTab: 'pageManage'
})

const editMethods = {
  add: () => {
    editState.operation = 'add'
    editState.title = '新增'
    copyValue(editForm, new EditForm())
    editState.visible = true
    setTimeout(() => {
      editFormRef.value?.clearValidate()
    })
  },
  update: (row: any) => {
    editState.operation = 'update'
    editState.title = '编辑'
    copyValue(editForm, row)
    editState.visible = true
    nextTick(() => {
      editFormRef.value?.clearValidate()
    })
  },
  submit: async () => {
    try {
      await editFormRef.value?.validate()
    }
    catch (err) {
      console.error(err)
      return
    }
    const params = {
      ...editForm
    }
    let res = null
    editState.loading = true
    if (editState.operation === 'add') {
      //
      res = await api.add(params)
    }
    else {
      //
      res = await api.update(params)
    }
    editState.loading = false
    if (!res.success) {
      //
      msgError(res.msg)
      return
    }
    msgSuccess(res.msg)
    methods.search()
    editMethods.close()
  },
  del: async (row: any) => {
    msgBoxWarnAsync('确认删除', '确定删除吗？', async () => {
      const { success, msg } = await api.del(row.id)
      if (success) {
        msgSuccess(msg)
        methods.search()
      }
      else {
        msgError(msg)
      }
    })

    // const res = await api.del(row.id)
    // if (!res.success) {
    //   //
    //   msgError(res.msg)
    //   return
    // }
    // msgSuccess(res.msg)
    // methods.search()
  },
  close: () => {
    editState.visible = false
  },
  details: (row: any, defaultTab: string = 'pageManage') => {
    state.row = row
    state.view = 'details'
    editState.defaultTab = defaultTab
  }
}
/** 编辑对话框 end */

/**
 * 创建应用
 */

const createApplication = async () => {
  const randomInt = Math.floor(Math.random() * 10000)
  const params = {
    name: `未命名应用${randomInt}`,
    type: 'PLATFORM',
    icon: 'ikflow-weixin'
  }

  const res = await api.add(params)
  if (!res.success) {
    msgError(res.msg)
    return
  }
  msgSuccess(res.msg)
  editMethods.details(res.data, 'pageManage')
}
</script>

<template>
  <Transition>
    <div v-if="state.view === 'table'">
      <IkPageMain fixed>
        <IkPageFull
          v-model="state.searchData"
          header-title="应用列表"
          :fields="state.fields"
          :table-data="state.tableData"
          :search="methods.search"
          :total="state.total"
        >
          <template #headerRight>
            <el-button type="primary" @click="createApplication">创建应用</el-button>
          </template>
          <template #name="{ data }">
            <IkSideText
              :avatar="data.row.icon"
              avatar-type="linearIcon"
              :name="data.row.name"
              :text="data.row.name"
              :icon-background-color="data.row.iconBackground"
              :sub-text="data.row.typeName"
            />
          </template>
          <template #operate="{ data }">
            <IkBtnContent :num="3">
              <IkTooltip :content="t('页面管理')">
                <IkSvgIcon
                  name="iksvg_bianji"
                  show-bg
                  @click="editMethods.details(data.row, 'pageManage')"
                />
              </IkTooltip>
              <IkTooltip :content="t('应用设置')">
                <IkSvgIcon
                  name="iksvg_shezhi"
                  show-bg
                  @click="editMethods.details(data.row, 'application')"
                />
              </IkTooltip>
              <IkTooltip :content="t('删除')">
                <IkSvgIcon
                  name="iksvg_shanchu1"
                  show-bg
                  @click="editMethods.del(data.row)"
                />
              </IkTooltip>
            </IkBtnContent>
          </template>
        </IkPageFull>
      </IkPageMain>

      <el-dialog v-model="editState.visible" :title="editState.title" :width="config.dialog.sl">
        <el-form
          ref="editFormRef"
          :model="editForm"
          label-position="top"
        >
          <el-form-item label="应用名称" prop="name" :rules="[{ required: true, message: '请输入应用名称' }]">
            <el-input
              v-model="editForm.name"
              placeholder="请输入应用名称"
              :maxlength="limitLength.lenName"
              show-word-limit
              clearable
            />
          </el-form-item>
          <el-form-item label="类型">
            <el-radio-group v-model="editForm.type">
              <el-radio v-for="item in typeOptions" :key="item.value" :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="首页地址">
            <el-input
              v-model="editForm.indexPath"
              placeholder="请输入首页地址"
              :maxlength="limitLength.lenLink"
              show-word-limit
              clearable
            />
          </el-form-item>
          <el-form-item label="图标">
            <IkFlowIconPicker v-model="editForm.icon" type="twoColor" />
          </el-form-item>
          <el-form-item label="描述">
            <el-input
              v-model="editForm.remark"
              type="textarea"
              placeholder="请输入描述"
              :maxlength="limitLength.lenContent"
              show-word-limit
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button bg text @click="editMethods.close">取消</el-button>
          <el-button :loading="editState.loading" type="primary" @click="editMethods.submit">确定</el-button>
        </template>
      </el-dialog>
    </div>
    <EditPage
      v-else
      class="edit-page"
      :application="state.row"
      :default-tab="editState.defaultTab"
      @back="methods.showTable"
    />
  </Transition>
</template>

<style lang="scss" scoped>
.edit-page{
  --ik-color-white: #fff;
}
</style>
